// Do not remove the include below
#include "tcpServer.h"
#include <JeeLib.h>

/*
 Web Server

 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)

 created 18 Dec 2009
 by David A. Mellis
 modified 4 Sep 2010
 by Tom Igoe

 */

#include <SPI.h>
#include <Ethernet.h>




// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,2,50);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(6789);
extern HardwareSerial Serial;

MilliTimer sendTimer;
MilliTimer sendTimer2;
byte sendSize;
char payload[] = "ABC 0123456789";
boolean needToSend = false;



void setEthernet(){
	if(needToSend){

		//sen(3) LOW && ss(10) HIGH to disable ethernet
				digitalWrite(3,LOW);
				digitalWrite(10,HIGH);
	}

	if(!needToSend){
		digitalWrite(3,HIGH);
						digitalWrite(10,LOW);

	}

}

void setup() {
	// start the Ethernet connection and the server:
	Ethernet.begin(mac, ip);
	server.begin();
	Serial.begin(57600);

	rf12_initialize(1, RF12_433MHZ, 33);
	pinMode(3, OUTPUT);
	pinMode(10, OUTPUT);



}

void loop() {
	if (sendTimer.poll(3000)) {
		needToSend = true;
		rf12_recvDone();
	}
	if(needToSend){
		setEthernet();
		if (rf12_canSend() ) {
				// send out a new packet every 3 seconds
				Serial.print("  send ");
				Serial.println((int) sendSize);
				// send as broadcast, payload will be encrypted
				rf12_sendStart(0, payload, sendSize + 4);
				needToSend = false;
				setEthernet();

			}
	}


	// listen for incoming clients
	EthernetClient client = server.available();
	if (client) {

		// an http request ends with a blank line
		boolean currentLineIsBlank = true;
		while (client.connected()) {
			String data;
			while (client.available() > 0) {
				char c = client.read();
				data += c;
			}

			if (data != "") {
				Serial.println(data);

				Serial.println(data.charAt(2));
				Serial.println(data.charAt(6));
				digitalWrite(data.charAt(2), data.charAt(6));
				data = "";
			}
		}

		// give the web browser time to receive the data
		delay(1);
		// close the connection:
		client.stop();
	}
}


